<!DOCTYPE html>
<html lang="zh">

	<head>
		<meta charset="UTF-8">
		<meta name="viewport"
			content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title style="font-size: 20px;"></title>

		<style type="text/css">
			html {
				height: 100%
			}

			body {
				height: 100%;
				margin: 0px;
				padding: 0px;
				overflow: hidden;
			}

			#map {
				width: 100%;
				height: 100%;
			}

			.btns {
				display: flex;
				flex-direction: column;
				z-index: 9999;
				position: absolute;
				bottom: 25%;
				right: 0%;
				width: 60px;
				overflow: hidden;
				align-items: center;
				display: none;
			}

			button {
				width: 46px;
				height: 46px;
				border-radius: 50%;
				outline: none;
				border: none;
				margin-bottom: 20px;
				background-color: #f1f1f1;
				color: #fff;
				z-index: 99999;

			}

			#phoneOrDevice {
				background-image: url("map/shebeiweizhi.png");
				background-size: 50%;
				background-repeat: no-repeat;
				/* 防止背景图片重复 */
				background-position: 50%;

			}

			#twoOrthreeD {
				background-image: url("map/a-2Dditu.png");
				background-size: 50%;
				background-repeat: no-repeat;
				/* 防止背景图片重复 */
				background-position: 50%;
			}

			#weilan {
				background-image: url("map/weilan-close.png");
				background-size: 50%;
				background-repeat: no-repeat;
				/* 防止背景图片重复 */
				background-position: 50%;

			}

			#navigation {
				background-image: url("map/daohang.png");
				background-size: 50%;
				background-repeat: no-repeat;
				/* 防止背景图片重复 */
				background-position: 50%;

			}

			.gm-control-active {
				display: none;
			}

			/* 信息提示样式 */
			/*
			 * Property styles in unhighlighted state.
			 */
			.property {
				display: flex;
				flex-direction: column;
				background-color: #fff;
				display: flex;
				transition: all 0.3s ease-out;
				border-radius: 5px;
				box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
			}

			.property::after {
				border-left: 9px solid transparent;
				border-right: 9px solid transparent;
				border-top: 9px solid #fff;
				content: "";
				height: 0;
				left: 50%;
				position: absolute;
				top: 95%;
				transform: translate(-50%, 0);
				transition: all 0.3s ease-out;
				width: 0;
				z-index: 1;
			}

			.property .icon {
				align-items: center;
				display: flex;
				justify-content: center;
				color: red;
			}

			.property .icon svg {
				height: 20px;
				width: auto;
			}

			.property .details {
				/* display: none; */
				top: -250%;
				position: absolute;
				background-color: #fff;
				padding: 10px;
			}


			/*
			 * Property styles in highlighted state.
			 */
			.property.highlight {
				background-color: #FFFFFF;
				border-radius: 8px;
				box-shadow: 10px 10px 5px rgba(0, 0, 0, 0.2);
				height: 80px;
				padding: 8px 15px;
				width: auto;
			}

			.property.highlight::after {
				border-top: 9px solid #FFFFFF;
			}

			.property.highlight .details {
				display: flex;
			}

			.property.highlight .icon svg {
				width: 50px;
				height: 50px;
			}

			.property .bed {
				color: #FFA000;
			}

			.property .bath {
				color: #03A9F4;
			}

			.property .size {
				color: #388E3C;
			}

			/*
			 * House icon colors.
			 */
			.property.highlight:has(.fa-house) .icon {
				color: var(--house-color);
			}

			.property:not(.highlight):has(.fa-house) {
				background-color: var(--house-color);
			}

			.property:not(.highlight):has(.fa-house)::after {
				border-top: 9px solid var(--house-color);
			}

			/*
			 * Building icon colors.
			 */
			.property.highlight:has(.fa-building) .icon {
				color: var(--building-color);
			}

			.property:not(.highlight):has(.fa-building) {
				background-color: var(--building-color);
			}

			.property:not(.highlight):has(.fa-building)::after {
				border-top: 9px solid var(--building-color);
			}

			/*
			 * Warehouse icon colors.
			 */
			.property.highlight:has(.fa-warehouse) .icon {
				color: var(--warehouse-color);
			}

			.property:not(.highlight):has(.fa-warehouse) {
				background-color: var(--warehouse-color);
			}

			.property:not(.highlight):has(.fa-warehouse)::after {
				border-top: 9px solid var(--warehouse-color);
			}

			/*
			 * Shop icon colors.
			 */
			.property.highlight:has(.fa-shop) .icon {
				color: var(--shop-color);
			}

			.property:not(.highlight):has(.fa-shop) {
				background-color: var(--shop-color);
			}

			.property:not(.highlight):has(.fa-shop)::after {
				border-top: 9px solid var(--shop-color);
			}


			.tips_box {
				background-color: #fff;
				width: 260px !important;
				border-radius: 6px;
				height: 100px;
				overflow: hidden;
			}

			.tips_header {
				background: #6ac695;
				color: #fff;
				height: 20px;
				padding: 5px;
				border-top-right-radius: 6px;
				border-top-left-radius: 6px;
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-size: 12px;
			}

			.tips_body {
				padding: 5px;
				font-size: 12px;
			}

			.tips_logo {
				width: 30px;
				height: 30px;
				border-radius: 50%;
				position: absolute;
				bottom: -32%;
				left: 45%;
			}

			#refreshLocation {
				width: 15px;
				height: 15px;
			}

			.spinner {
				width: 15px;
				height: 15px;
				animation: spin 1s linear infinite;
			}
			@keyframes spin {
				0% {
					transform: rotate(0deg);
				}

				100% {
					transform: rotate(360deg);
				}
			}

			.gm-style iframe+div {
				border: none !important;
			}

			a[href^="http://maps.google.com/maps"] {
				display: none !important
			}

			a[href^="https://maps.google.com/maps"] {
				display: none !important
			}

			.gmnoprint a,
			.gmnoprint span,
			.gm-style-cc {
				display: none;
			}

			.gmnoprint div {
				background: none !important;
			}
		</style>
	</head>

	<body>

		<div id='map'></div>
		<div class="btns" id="btnBg">
			<button id="phoneOrDevice"> </button>
			<button id="twoOrthreeD"> </button>
			<button id="weilan"> </button>
			<button id="navigation"> </button>
		</div>

	</body>

	<script type="text/javascript" src="../uni.webview.1.5.2.js">

	</script>
	<script>
		(g => {
			var h, a, k, p = "The Google Maps JavaScript API",
				c = "google",
				l = "importLibrary",
				q = "__ib__",
				m = document,
				b = window;
			b = b[c] || (b[c] = {});
			var d = b.maps || (b.maps = {}),
				r = new Set,
				e = new URLSearchParams,
				u = () => h || (h = new Promise(async (f, n) => {
					await (a = m.createElement("script"));
					e.set("libraries", [...r] + "");
					for (k in g) e.set(k.replace(/[A-Z]/g, t => "_" + t[0].toLowerCase()), g[k]);
					e.set("callback", c + ".maps." + q);
					a.src = `https://maps.${c}apis.com/maps/api/js?` + e;
					d[q] = f;
					a.onerror = () => h = n(Error(p + " could not load."));
					a.nonce = m.querySelector("script[nonce]")?.nonce || "";
					m.head.append(a)
				}));
			d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n) => r.add(f) && u().then(() => d[
				l](f, ...n))
		})({
			key: "AIzaSyCaJJDLbPygLYHFL1vi6AlcQmR1P1rRDvA",
			v: "weekly",
			// Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).
			// Add other bootstrap parameters as needed, using camel case.
		});
	</script>
	<script type="text/javascript">
		// 获取url参数
		function getUrlParams(url) {
			const paramsRegex = /[?&]+([^=&]+)=([^&]*)/gi;
			const params = {};
			let match;
			while (match = paramsRegex.exec(url)) {
				params[match[1]] = match[2];
			}
			return params;
		}

		var map;
		// 加载地图
		var currentPostion;
		var geocoder;
		var currentAddress;
		var currentTime;
		// 创建标记 和提示框
		var marker;
		var properties;
		var showDevicePostion = true;
		var signalType; //信号类型
		var speed = 0; //速度
		var errormeter = 0;
		var circlesArr = [];
		var fencemarkerArr = [];
		var fenceList = [];
		let timeOut ;
		//初始化地图
		async function initMap() {
			const {
				Map
			} = await google.maps.importLibrary("maps");
			const {
				ColorScheme
			} = await google.maps.importLibrary("core")


			map = new Map(document.getElementById("map"), {
				zoom: 15,
				mapId: '9acf2d6299ded60c',//"4504f8b37365c3d0"
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				streetViewControl: false,
				zoomControl: false,
				mapTypeControl: false,
				fullscreenControl: false,
				scaleControl: false,
				rotateControl: true,
				clickableIcons: false,
				center: currentPostion,
				// colorScheme: ColorScheme.DARK,

			});

		}


		//获取手机当前时间
		function getCurrentTime() {
			var currentDate = new Date();
			// 获取年、月、日、小时、分钟、秒
			var year = currentDate.getFullYear();
			var month = currentDate.getMonth() + 1; // 月份是从0开始的
			var day = currentDate.getDate();
			var hours = currentDate.getHours();
			var minutes = currentDate.getMinutes();
			var seconds = currentDate.getSeconds();

			// 格式化为YYYY-MM-DD HH:MM:SS
			var formattedDate = year + '-' + month.toString().padStart(2, '0') + '-' + day.toString().padStart(2, '0') + ' ' +
				hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0') + ':' + seconds.toString()
				.padStart(2, '0');

			return formattedDate;
		}

		function timestampToDateTime(timestamp) {

			var date = new Date(Number(timestamp)); // 转换为Date对象
			var year = date.getFullYear(); // 获取年份
			var month = ("0" + (date.getMonth() + 1)).slice(-2); // 获取月份，转为两位数
			var day = ("0" + date.getDate()).slice(-2); // 获取日，转为两位数
			var hours = ("0" + date.getHours()).slice(-2); // 获取小时，转为两位数
			var minutes = ("0" + date.getMinutes()).slice(-2); // 获取分钟，转为两位数
			var seconds = ("0" + date.getSeconds()).slice(-2); // 获取秒，转为两位数

			// 生成格式化的日期字符串
			return year + "-" + month + "-" + day + "   " + hours + ":" + minutes + ":" + seconds;
		}

		function formatUTCTime(timestamp) {
			if (!timestamp) {
				return '-';
			}
			// 创建Date对象并传入UTC时间作为参数
			const date = new Date(Number(timestamp));
			// // 获取当地时间偏移
			// const offset = date.getTimezoneOffset();
			// console.log("offSet===",offset);
			// // 根据偏移调整时间
			// date.setMinutes(date.getMinutes() - offset);
			// 将时间转换为当地标准时间的字符串表示
			const year = date.getFullYear();
			const month = (date.getMonth() + 1).toString().padStart(2, '0');
			const day = date.getDate().toString().padStart(2, '0');
			const hours = date.getHours().toString().padStart(2, '0');
			const minutes = date.getMinutes().toString().padStart(2, '0');
			const seconds = date.getSeconds().toString().padStart(2, '0');
			const localTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			return localTime
		}

		//获取当前手机位置
		async function getPhonePostion() {

			//获取当前时间 
			currentTime = getCurrentTime();


			if (navigator.geolocation) {

				navigator.geolocation.getCurrentPosition(function(position) {
					console.log('position', position);
					currentPostion = {
						lat: position.coords.latitude,
						lng: position.coords.longitude
					};
					errormeter = position.coords.accuracy;
					getAddressName();
				}, function() {
					handleLocationError(true, map.getCenter());
				});
			} else {
				// 浏览器不支持地理定位
				handleLocationError(false, map.getCenter());
			}
		}

		// 处理地理定位错误
		function handleLocationError(browserHasGeolocation, infoWindow, pos) {
			infoWindow.setPosition(pos);
			infoWindow.setContent(browserHasGeolocation ?
				'Error: The Geolocation service failed.' :
				'Error: Your browser doesn\'t support geolocation.');
		}

		async function getAddressName() {

			const {
				Geocoder
			} = await google.maps.importLibrary("geocoding");
			const geocoder = new Geocoder();
			geocoder.geocode({
				'location': currentPostion
			}, function(results, status) {
				if (status === google.maps.GeocoderStatus.OK) {
					if (results[0]) {
						let currentAddressInfo = results[0].formatted_address;
						let arr = currentAddressInfo.split(" ");
						currentAddress = arr[0];
						createMarker();
						// console.log(results[0].formatted_address); // 地名
					} else {
						console.log('No results found');
					}
				} else {
					console.log('Geocoder failed due to: ' + status);
				}
			});
		}


		async function createMarker() {
			const {
				AdvancedMarkerElement
			} = await google.maps.importLibrary("marker");
			if (marker) {
				marker.setMap(null)
			}
			// 将地图中心设置为获取到的位置
			map.setCenter(currentPostion);
			marker = new google.maps.marker.AdvancedMarkerElement({
				map,
				content: buildContent(properties),
				position: currentPostion,
			});

			//监听点击
			marker.addListener("click", () => {

				if (showDevicePostion) {
					document.getElementById('refreshLocation').classList.add('spinner');
					timeOut = setTimeout(()=>{
						stopIconTransform();
					},60000)
					uni.postMessage({
						data: {
							msg: "getDevicePostion",
						}
					})
				} else {
					getPhonePostion();
				}

			});
		}
		
		function stopIconTransform(){
			document.getElementById('refreshLocation').classList.remove('spinner');
			clearTimeout(timeOut);
			timeOut = null;
		}


		// 绘制信息提示框
		function buildContent(property) {
			const content = document.createElement("div");
			content.classList.add("property");
			content.innerHTML = `
			<div class='tips_box'>
				<div class='tips_header'>
					<div>date time:${currentTime}</div>
					<img id="refreshLocation" src='map/refresh_pos.png'/>
				</div>
				<div class='tips_body'>
					<div>speed:${properties.speed} km/h</div>
					<div>${signalType}${errormeter}meters error</div>
					<div>${currentAddress}</div>
				</div>
			</div>
			<img class='tips_logo' id='dev_logo' src='${headUrl}'/>
		    `;
			return content;
		}
		var headUrl;
		//手机或设备切换
		var phone_device_button = document.getElementById('phoneOrDevice');
		var phone_device_currentBg = 'url(map/shebeiweizhi.png)'; // 初始背景图

		phone_device_button.addEventListener('click', function() {
			if (phone_device_currentBg === 'url(map/shebeiweizhi.png)') {
				showDevicePostion = false;
				getPhonePostion();
				phone_device_currentBg = 'url(map/phonelocation.png)'; // 更换背景图
				headUrl = 'map/map_phone.png';
			} else {
				showDevicePostion = true;
				uni.postMessage({
					data: {
						msg: "getDeviceDeviceInfo",
					}
				})
				phone_device_currentBg = 'url(map/shebeiweizhi.png)'; // 恢复原背景图
			}
			this.style.backgroundImage = phone_device_currentBg; // 应用背景图
		});
		//2D或3D切换
		var twoOrthreeD_button = document.getElementById('twoOrthreeD');
		var twoOrthreeD_currentBg = 'url(map/a-2Dditu.png)'; // 初始背景图    
		twoOrthreeD_button.addEventListener('click', function() {
			map.setCenter(currentPostion);
			if (twoOrthreeD_currentBg === 'url(map/a-2Dditu.png)') {
				map.setMapTypeId('satellite');

				map.setTilt(45);
				twoOrthreeD_currentBg = 'url(map/a-3dditu.png)'; // 更换背景图
			} else {
				map.setMapTypeId('roadmap');
				map.setTilt(0);

				twoOrthreeD_currentBg = 'url(map/a-2Dditu.png)'; // 恢复原背景图
			}
			this.style.backgroundImage = twoOrthreeD_currentBg; // 应用背景图
		});


		//电子围栏显示 或关闭
		var weilan_button = document.getElementById('weilan');
		var weilan_button_currentBg = 'url(map/weilan-close.png)'; // 初始背景图    
		weilan_button.addEventListener('click', function() {
			if (fenceList.length == 0) {
				alert("No fence available for display");
				return;
			}
			if (weilan_button_currentBg === 'url(map/weilan-close.png)') {
				showDeviceFence();
				weilan_button_currentBg = 'url(map/a-mianxingonkaiqion.png)'; // 更换背景图
			} else {
				removeDeviceFence();
				weilan_button_currentBg = 'url(map/weilan-close.png)'; // 恢复原背景图
			}
			this.style.backgroundImage = weilan_button_currentBg; // 应用背景图
		});
		// gpsFlag":1 //1GPS，2WIFI,3基站，4WIFI+基站

		function getSignalType(gpsFlag,radius) {
			if(gpsFlag){
				switch (gpsFlag) {
					case 1:
						return 'gps: ';
						break;
					case 2:
						return 'wifi: ';
						break;
					case 3:
						return 'wifi: ';
						break;
					case 4:
						return 'wifi: ';
						break;
					default:
						break;
				}
			}else{
				if(radius < 25){
					return "gps: "
				}else{
					return "wifi: "
				}
			}
			

		}

		async function showDeviceFence() {
			const {
				AdvancedMarkerElement
			} = await google.maps.importLibrary("marker");


			fenceList.forEach(function(item, index) {
				const fenceCircle = new google.maps.Circle({
					strokeColor: "#FF0000",
					strokeOpacity: 0.8,
					strokeWeight: 2,
					fillColor: "#FF0000",
					fillOpacity: 0.35,
					map,
					center: {
						lat: item.lat,
						lng: item.lng,
					},
					radius: item.radius,
				});
				const marker = new google.maps.marker.AdvancedMarkerElement({
					map,
					// content: buildContent(properties),
					position: {
						lat: item.lat,
						lng: item.lng,
					},
				});
				fencemarkerArr.push(marker);
				circlesArr.push(fenceCircle);
			})
		}
		function removeDeviceFence() {
			for (var i = 0; i < circlesArr.length; i++) {
				circlesArr[i].setMap(null);
				fencemarkerArr[i].setMap(null);
			}
		}
		window.addEventListener('UniAppJSBridgeReady', function() {
			uni.postMessage({
				data: {
					msg: "finishloaded",
				}
			})
			window.getVueMessage = (data) => {
				console.log('收到APP消息', JSON.stringify(data));
				if (data.type == 1) {
					properties = data.msg;
					headUrl = properties.headUrl;
					if(!headUrl){
						headUrl = "../device/device_icon.png";
					}
					
					currentPostion = {
						lat: Number(properties.lat),
						lng: Number(properties.lng),
					};
					speed = properties.speed;
					currentTime = formatUTCTime(properties.locTime);
					signalType = getSignalType(properties.gpsFlag,properties.radius);
					errormeter = properties.radius; //properties.gpsFlag == 1 ? 30 :

					if (!map) {
						initMap();
					}
					document.getElementById("map").style.display = "block";
					getAddressName();
					document.getElementById("btnBg").style.display = "block";
					document.getElementById('phoneOrDevice').style.backgroundImage = 'url(map/shebeiweizhi.png)';
				} else if (data.type == 2) {
					document.getElementById("btnBg").style.display = "none";
					currentPostion = {
						lat: Number(data.msg.lat),
						lng: Number(data.msg.lng),
					};
					document.getElementById("map").style.display = "block";
					initMap();
				} else if (data.type == 3) {
					fenceList = data.msg;
				} else if (data.type == 4) {
					stopIconTransform();
				}else if(data.type == 5){
					document.getElementById("map").style.display = "none";
					document.getElementById("btnBg").style.display = "none";
				}
			}
			//导航
			document.getElementById('navigation').onclick = function() {
				uni.postMessage({
					data: {
						msg: "navigation",
						address: currentAddress,
						position: currentPostion.lat.toString() + ',' + currentPostion.lng.toString()
					}
				})
			}
		});

		document.addEventListener('gesturestart', function(event) {
			event.preventDefault()
		})
	</script>